<?php
class Link_Model extends MY_Model {
	var $_table = "links";
	var $_table_meta = "links_meta";
	var $_field_meta_rel = "link_id";
	
	function Link_Model(){
		parent::Model();
	}
	
	function get($params = array(), $start = -1, $offset = -1){
		$params = $this->_getParams($params);
		
		$DB = $this->_get($params);
		
		$DB->select ( $this->_table . ".*" );
		
		if ($start != - 1 && $offset != - 1) {
			$DB->limit ( $offset, $start );
		}
		
		$query = $DB->get ();
		
		if((isset($params['id']) && $params['id'] != NULL && $params['id'] !=-1) ||
			(isset($params['url_name']) && $params['url_name'] != NULL)){
				
			if ($query->num_rows() > 0){
				$data_cache = $query->row();
			} else{
				$data_cache = NULL;
			}
			
		} else{
			$data_cache = $query->result ();
		}
		
		return $data_cache;
	}
	
	function getCount($params = array()){
		$params = $this->_getParams($params);
		
		$DB = $this->_get($params);

		$data_cache = $DB->count_all_results ();
	}
	
	function _getParams($params = array()){
		$defaults = array(
			"id"			=> NULL,
			"url"			=> NULL,
			"status" 		=> "visible", //no_visible, all		
			"categories"	=> array(),
			"categories_or"	=> array(),
		 
			"order"			=> array(
				"link_name"	=> "asc"
			)
		);
		
		$params = array_merge($defaults, $params);
		
		if($params['categories'] != NULL && is_string($params['categories'])){
			$params['categories'] = split(",", $params['categories']);
		}
		if($params['categories_or'] != NULL && is_string($params['categories_or'])){
			$params['categories_or'] = split(",", $params['categories_or']);
		}
		
		return $params;
	}
	
	function _get($params = array()){
		$this->db->from ( $this->_table );
		
		if($params['status'] != NULL && $params['status'] != "all" ){
			if($params['status'] == "visible"){
				$this->db->where("$this->_table.link_status = active");
			} else if($params['status'] == "no_visible"){
				$this->db->where("$this->_table.link_status = inactive");
			}
		}
		
		if($params['id'] != NULL && $params['id'] != -1){
			$this->db->where ( "$this->_table.link_id", $params['id'] );
		} else if($params['url'] != NULL && $params['url'] != ""){
			$this->db->where ( "{$this->_table}.link_url", $params['url'] );
		} else{
			
			if($params['categories'] != NULL && is_array($params['categories']) && count($params['categories'])>0){
				foreach($params['categories'] as $pos=>$category){
					$this->db->join ( "links_categories as lc_$pos", "lc_$pos.link_id = " . $this->_table . ".id" );
					
					if(is_numeric($category)){
						$this->db->where("lc_$pos.link_id", $category);
					} else{
						$this->db->join ( "categories as c_$pos", "c_$pos.id = " . "lc_$pos.category_id" );
						$this->db->where ( "c_$pos.url_name", $category );
					}
				}
			}
			
			if($params['categories_or'] != NULL && is_array($params['categories_or']) && count($params['categories_or'])>0){
				$this->db->join ( "links_categories as lc_or", "lc_or.link_id = " . $this->_table . ".id" );
				$this->db->join ( "categories as c_or", "c_or.id = " . "lc_or.category_id" );
				
				$where_query = "(";
				$num_params = count($params['categories_or']);
				foreach($params['categories_or'] as $pos=>$category){
					if(is_numeric($category)){
						$where_query .= "c_or.id = $category";
					} else{
						$where_query .= "c_or.url_name = '$category'";
					}
					if($pos<($num_params - 1)){
						$where_query .= " OR ";
					}
				}
				$where_query .= ")";
				
				$this->db->where($where_query);
			}
			
			if($params['order'] != NULL){
				foreach($params['order'] as $field => $direction){
					$this->db->order_by ( "$field $direction" );
				}
			}
		}
		
		return $this->db;
	}
	
	function create($field_data = array()){
		$defaults = array(
			"url" => "url", "name" => "tmp", 
			"target" => "", "status" => "inactive",
			'created' => mdate($this->_dateFormat), 'modified' => mdate($this->_dateFormat),
			"metas" => array()
		);
		
		$field_data = array_merge($defaults, $field_data);
		
		$data = array(
			"link_name"		=> $field_data['name'], 
			"link_url"		=> $field_data['url'], 
			"link_target"	=> $field_data['target'], 
			"link_status"	=> $field_data['status'], 
		
			"link_created"	=> $field_data['created'],
			"link_modified"	=> $field_data['modified']
		);
		
		$this->db->insert($this->_table, $data);
		
		$id = $this->db->insert_id();
		
		if($field_data['metas'] != NULL){
			foreach($node_data['metas'] as $key=>$value){
				$this->addMeta($id, $key, $value);
			}
		}
		
		return $id;		
	}
	
	function update($field_data = array()){
		$element = $this->get(array("id" => $field_data['id'], "status" => "all"));
		
		if($element != NULL){
			$defaults = array(
				'name'		=> $element->link_name,
				'url'		=> $element->link_url,
				'target'	=> $element->link_target,
				'status'	=> $element->link_status,
				'modified'	=> mdate($this->_dateFormat),
				'metas'		=> array()
			);
			
			$field_data = array_merge($defaults, $field_data);
			
			$data = array (
				'link_name'		=> $field_data['name'],
				'link_url'		=> $field_data['url'],
				'link_target'	=> $field_data['target'],
				'link_status'	=> $field_data['status'],
				'link_modified' => $field_data['modified']
			);
			
			$this->db->where('link_id', $field_data['id']);
			$this->db->update($this->_table, $data);
			
			if($field_data['metas'] != NULL){
				foreach($data['metas'] as $key=>$value){
					$this->addMeta($field_data['id'], $key, $value);
				}
			}
		}
		
		return FALSE;
	}
	
	function delete($id = NULL){
		$this->db->delete($this->_table, array('link_id' => $id));
		$this->db->delete($this->_table_meta, array($this->_field_meta_rel => $id));
	}
	
	function getCategories($id){
		$this->db->select ( "*" );
		$this->db->from ( "categories" );
		$this->db->join ( "links_categories as lc", "lc.category_id = categories.id" );
		$this->db->where ( "lc.link_id", $id );

		$query = $this->db->get ();
		
		return $query->result ();
	}
	
	function addCategories($id, $categories = NULL){
		if($categories != NULL){
			foreach($categories as $category){
				$this->addCategory($id, $category);
			}
		}
	}
	
	function addCategory($id, $idCategory){
		//Vamos a comprobar que no estubieran previamente asociados
		$categories = $this->getCategories($id);
		
		if($categories != NULL){
			foreach($categories as $category){
				if($category->id == $idCategory){
					return;
				}
			}
		}
		$data = array (
			'link_id' => $id,
			'category_id' => $idCategory
		);

		$this->db->insert("links_categories", $data);
	}
	
	function deleteCategory($id, $idCategory){
		$this->db->delete("links_categories", array('link_id' => $id, 'category_id' => $idCategory));
	}
	
	function deleteCategories($id){
		$this->db->delete("links_categories", array('link_id' => $id));
	}
	
}